<script setup>
import {inject, onMounted, onUnmounted, provide, ref} from 'vue';
import useDesignerStore from '../../store/index';
import AILabel from '../../common/libs/AILabel/main';
import LeftMenu from "../../components/designer/LeftMenu";
import TopMenuBar from "../../components/designer/TopMenuBar";
import ThumbnailListBar from "../../components/designer/ThumbnailListBar";
import RightPanel from "../../components/designer/RightPanel";
import ElMessage, {ElMessageBox} from "element-plus";
import BottomBar from "../../components/designer/BottomBar";
import ImageTool from "../../common/ImageTool"; // 确保这是正确的导入路径

const designerStore = useDesignerStore();
// 声明一个响应式引用，但在这个场景中我们实际上不需要它，因为 AILabel 将直接操作 DOM
const mapContainerRef = ref(null);

const gMapProvide=ref(null);
const imgUrl = '/2fab4e01e98b4140b4a383b926131de8.jpg';
const drawingStyle = ref({});
const gFirstFeatureLayer=ref(null);
const gFirstMaskLayer=ref(null);
const gFirstTextLayer=ref(null);
const deleteIconId=ref(null);
const allFeatures = ref([]);
const itemName = ref("");



provide('gMap', gMapProvide);
provide('gFirstFeatureLayer', gFirstFeatureLayer);
provide('gFirstMaskLayer', gFirstMaskLayer);
provide('gFirstTextLayer', gFirstTextLayer);

// 获取所有features
const getFeatures=()=> {
  allFeatures.value = gFirstFeatureLayer.value.getAllFeatures();
  console.log("--allFeatures--", allFeatures.value);
}

const setDrawingStyle = (mode) => {
  switch (mode) {
      //平移
    case "PAN": {
      break;
    }
      //注记
    case "MARKER": {
      // 忽略
      break;
    }
      //点
    case "POINT": {
      drawingStyle.value = { fillStyle: "#FF8C00" };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
      //圆
    case "CIRCLE": {
      drawingStyle.value = {
        fillStyle: "#87CEFF",
        strokeStyle: "#87CEFF",
        lineWidth: 5,
      };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
      //线段
    case "LINE": {
      drawingStyle.value = {
        strokeStyle: "#BA55D3",
        lineJoin: "round",
        lineCap: "round",
        lineWidth: 10,
        arrow: false,
      };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
      //多线段
    case "POLYLINE": {
      drawingStyle.value = {
        strokeStyle: "#FF1493",
        lineJoin: "round",
        lineCap: "round",
        lineWidth: 10,
      };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
      //矩形
    case "RECT": {
      drawingStyle.value = { strokeStyle: "#0f0", lineWidth: 1 };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
      //多边形
    case "POLYGON": {
      drawingStyle.value = {
        strokeStyle: "#0099CC", //边框颜色
        fill: true, //是否填充
        fillStyle: "#FF6666", //填充色
        globalAlpha: 0.3,
        lineWidth: 3,
        stroke: true,
      };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
      //涂抹
    case "DRAWMASK": {
      drawingStyle.value = {
        strokeStyle: "rgba(255, 0, 0, .5)",
        fillStyle: "#00f",
        lineWidth: 50,
      };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
      //擦除
    case "CLEARMASK": {
      drawingStyle.value = { fillStyle: "#00f", lineWidth: 30 };
      gMapProvide.value.setDrawingStyle(drawingStyle.value);
      break;
    }
    default:
      break;
  }
};

const addFeature=(data, type, id)=>{
  //线
  if (type === "LINE") {
    const scale = gMapProvide.value.getScale();
    const width = drawingStyle.value.lineWidth / scale;
    const lineFeature = new AILabel.Feature.Line(
        id, // id
        { ...data, width }, // shape
        { name }, // props
        drawingStyle.value // style
    );
    gFirstFeatureLayer.value.addFeature(lineFeature);
  }
  //线段
  else if (type === "POLYLINE") {
    const scale = gMap.getScale();
    const width = drawingStyle.value.lineWidth / scale;
    const polylineFeature = new AILabel.Feature.Polyline(
        id, // id
        { points: data, width }, // shape
        { name }, // props
        drawingStyle.value // style
    );
    gFirstFeatureLayer.value.addFeature(polylineFeature);
  }
  //矩形
  else if (type === "RECT") {
    const rectFeature = new AILabel.Feature.Rect(
        id, // id
        data, // shape
        { name }, // props
        drawingStyle.value // style
    );
    gFirstFeatureLayer.value.addFeature(rectFeature);
  }
  //多边形
  else if (type === "POLYGON") {
    const polygonFeature = new AILabel.Feature.Polygon(
        id, // id
        { points: data }, // shape
        { name }, // props
        drawingStyle.value // style
    );
    gFirstFeatureLayer.value.addFeature(polygonFeature);
  }
  //点
  else if (type == "POINT") {
    const gFirstFeaturePoint = new AILabel.Feature.Point(
        id, // id
        { x: data.x, y: data.y, r: 5 }, // shape
        { name }, // props
        { fillStyle: "#FF8C00", zIndex: 5, lineWidth: 2 } // style
    );
    gFirstFeatureLayer.value.addFeature(gFirstFeaturePoint);
  }
  //注记
  else if (type == "MARKER") {
    const gFirstMarker = new AILabel.Marker(
        id, // id
        {
          src: "http://ailabel.com.cn/public/ailabel/demo/marker.png",
          position: {
            // marker坐标位置
            x: data.x,
            y: data.y,
          },
          offset: {
            x: -16,
            y: 32,
          },
        }, // markerInfo
        { name: "第一个marker注记" } // props
    );
    gFirstFeatureLayer.value.addFeature(gFirstMarker);
  }
  //圆
  else if (type == "CIRCLE") {
    const gFirstFeatureCircle = new AILabel.Feature.Circle(
        id, // id
        { cx: data.cx, cy: data.cy, r: data.r }, // shape
        { name: "第一个矢量图层" }, // props
        {
          fillStyle: "#87CEFF",
          strokeStyle: "#3CB371",
          globalAlpha: 1,
          lineWidth: 5,
        } // style
    );
    gFirstFeatureLayer.value.addFeature(gFirstFeatureCircle);
  }
  //涂抹
  else if (type == "DRAWMASK") {
    const drawMaskAction = new AILabel.Mask.Draw(
        `${+new Date()}`, // id
        "铅笔",
        { points: data, width: 5 }, // shape
        { name: "港币", price: "1元" }, // props
        { strokeStyle: "#FF0000" } // style
    );
    gFirstFeatureLayer.value.addAction(drawMaskAction);
  }
  //擦除
  else if (type == "CLEARMASK") {
    const clearMaskAction = new AILabel.Mask.Clear(
        "first-action-clear", // id
        { points: data, width: 5 } // shape
    );
    gFirstMaskLayer.addAction(clearMaskAction);
  }
  getFeatures();
}

// 画完取名
const getName=(mode)=> {
  return ElMessageBox.prompt("请输入填写名字", {
    confirmButtonText: "确定",
    showCancelButton: false,
  })
      .then(({ value }) => {
        itemName.value = value;
        return value;
      })
      .catch(() => {
        return null;
      });
}
// 增加删除图标
const addDeleteIcon=(feature, shape)=>{
  // 添加delete-icon
  let points = getPoints(feature);
  console.log(shape, "shape");
  const gFirstMarker = new AILabel.Marker(
      deleteIconId.value, // id
      {
        src: "https://s1.ax1x.com/2022/06/20/XvFRbT.png",
        position: points, // 矩形右上角 根据图形动态调整
        offset: {
          x: -20,
          y: -4,
        },
      }, // markerInfo
      { name: "delete" } // props
  );
  gFirstMarker.events.on("click", (marker) => {
    // 首先删除当前marker
    gMapProvide.value.markerLayer.removeMarkerById(marker.id);
    // 删除对应text
    // gFirstTextLayer.removeTextById(textId);
    // 删除对应feature
    gFirstFeatureLayer.value.removeFeatureById(feature.id);
  });
      gMapProvide.value.markerLayer.addMarker(gFirstMarker);

  // that.gFirstFeatureLayer
}
// 删除 删除按钮
const deIcon=()=> {
      gMapProvide.value.markerLayer.removeAllMarkers();
}
// 增加事件
const addEvent=() =>{
  // 绘制结束时触发
  gMapProvide.value.events.on("drawDone", (type, data) => {
    console.log("--type, data--", type, data);
    // that.addFeature(data, type);
    if (type == "CLEARMASK" || type == "DRAWMASK") {
      addFeature(data, type);
    } else {
      getName(type).then((id) => {
        if (id) {
          addFeature(data, type, id);
        } else {
          ElMessageBox.alert("取消添加");
        }
      });
    }
  });
  // 视野范围发生变化
  gMapProvide.value.events.on("boundsChanged", () => {
    onBottomInfo();
    return "";
  });
  // 在绘制模式下双击feature触发选中
  gMapProvide.value.events.on("featureSelected", (feature) => {
    designerStore.currentFeatureId = feature.id;
    designerStore.currentFeature = feature;
    console.log("--map featureSelected--", feature, "双击编辑");
    //设置编辑feature
    gMapProvide.value.setActiveFeature(feature);
    if (feature.type != "POINT") {
      // 增加删除按钮
      addDeleteIcon(feature, feature.shape);
    }
  });
  // 当模式切换或单击其他地方触发
  gMapProvide.value.events.on("featureUnselected", () => {
    // 取消featureSelected
    designerStore.currentFeatureId = "";
    designerStore.currentFeature = null;
    deIcon();
    gMapProvide.value.setActiveFeature(null);
  });
  //右键 目前只针对点双击选中右键触发
  gMapProvide.value.events.on("featureDeleted", (feature) => {
    if (feature.type == "POINT") {
      // 根据id删除对应feature
      gFirstFeatureLayer.value.removeFeatureById(feature.id);
    }
  });
  // feature编辑完成触发
  gMapProvide.value.events.on("featureUpdated", (feature, shape) => {
    console.log(feature);
    // 更新或者移动需要重新设置删除图标
    deIcon();
    feature.updateShape(shape);
    if (feature.type != "POINT") {
      addDeleteIcon(feature, shape);
    }
  });

  // 目前只针对点双击选中右键触发
  gMapProvide.value.events.on("FeatureDeleted", () => {
    console.log(2222222);
    gFirstFeatureLayer.value.removeFeatureById(designerStore.currentFeatureId);
  });

  //拖动feature(dbclick之后)
  gMapProvide.value.events.on("draging", (feature) => {
    console.log("--draging--", feature);
  });

  // 单击事件
  gMapProvide.value.events.on("click", (data) => {
    console.log("--map click--", data);
  });
  // 双击事件
  gMapProvide.value.events.on("dblClick", (data) => {
    console.log("--map dblclick--", data);
  });
  // 右键事件
}

const onBottomInfo=()=>{
  designerStore.bounds = gMapProvide.value.getBounds();
  designerStore.screenCenter = gMapProvide.value.getScreenCenter();
  designerStore.center = gMapProvide.value.getCenter();
  designerStore.scale = gMapProvide.value.getScale();
  designerStore.containerSize = gMapProvide.value.getSize();
}
// 获取坐标 需要自行添加
const getPoints=(feature) =>{
  switch (feature.type) {
    case "RECT":
      return feature.getPoints();
    case "LINE":
      return [feature.shape.start, feature.shape.end];
    case "POLYLINE":
      return feature.shape.points;
    case "POLYGON":
      return feature.shape.points;
    default:
      return [];
  }
}
//填充事件
const Fill=()=> {
  console.log("填充事件");
  let fill = gFirstFeatureLayer.value.getFeatureById(designerStore.currentFeatureId);
  console.log("--填充对象--", fill);
  fill.style.fillStyle = "#FFDAB9";
  fill.style.fill = true;
  //刷新map
      gMapProvide.value.refresh();
}
//撤销
const Revoke=()=> {
  console.log("撤销");
  getFeatures();
  allFeatures.value.pop();
  //刷新map
  gMapProvide.value.refresh();
  console.log(allFeatures.value, "--所有操作--");
}
//恢复
const Restore=()=> {
  console.log("恢复");
  allFeatures.value.pop();
  //刷新map
}
provide('Revoke', Revoke);
provide('Fill', Fill);

// 初始化地图的函数
const initMap = () => {
  gMapProvide.value = new AILabel.Map("map-container", {
    center: { x: window.innerWidth / 2, y: window.innerHeight / 2 },
    zoom: 800,
    mode: 'PAN',
    refreshDelayWhenZooming: true, // 缩放时是否允许刷新延时，性能更优
    zoomWhenDrawing: true,
    panWhenDrawing: true,
    zoomWheelRatio: 5, // 控制滑轮缩放缩率[0, 10), 值越小，则缩放越快，反之越慢
    withHotKeys: true, // 关闭快捷键
  });
  onBottomInfo();
  addEvent();

  // 添加矢量图层
  gFirstFeatureLayer.value = new AILabel.Layer.Feature(
      "first-layer-feature", // id
      { name: "第一个矢量图层" }, // props
      { zIndex: 10 } // style
  );
  gMapProvide.value.addLayer(gFirstFeatureLayer.value);

  gFirstTextLayer.value = new AILabel.Layer.Text(
      'first-layer-text', // id
      {name: '第一个文本图层'}, // props
      {zIndex: 12, opacity: 1} // style
  );
  gMapProvide.value.addLayer(gFirstTextLayer.value);

  window.onresize = function () {
    gMapProvide.value && gMapProvide.value.resize();
  };
};

// 在组件挂载后初始化地图
onMounted(() => {
  initMap();
});

onUnmounted(() => {
  gMapProvide.value && gMapProvide.value.destroy();
  gMapProvide.value = null;
  mapContainerRef.value = null;
  window.onresize = null;
});
</script>

<template>
  <div class="designer-index">
    <!-- 左侧菜单栏 -->
    <LeftMenu />
    <!-- 顶部菜单栏 -->
    <TopMenuBar />
    <!-- 缩略图列表 -->
    <ThumbnailListBar />
    <!-- 右侧信息设置面板 -->
    <RightPanel />

    <!-- 使用 ref 属性将 DOM 元素与响应式引用关联 -->
    <div ref="mapContainerRef" id="map-container"></div>

    <!-- 底部工具栏 -->
    <BottomBar />
  </div>
</template>

<style lang="scss" scoped>
.designer-index {
  position: relative;
  overflow: hidden;
  width: 100vw;
  height: 100vh;
  #map-container {
    width: 100%;
    height: 100%;
    //position: relative;
    overflow: hidden;
  }
}

</style>